home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / ProgramD2.iso / Borland / Borland C++ V5.02 / STDLIB.PAK / MUTEX.CPP < prev    next >
C/C++ Source or Header  |  1997-05-06  |  721b  |  41 lines

  1. //
  2. // This is a code snippet illustrating how to use mutexes to
  3. // synchronize resources in a multi-threaded program.
  4. //
  5.  
  6. #include <stdmutex.h>
  7.  
  8. //
  9. // An integer shared amongst multiple threads.
  10. //
  11. int I;
  12.  
  13. //
  14. // A mutex used to synchronize updates to I.
  15. //
  16. RWSTDMutex I_mutex;
  17.  
  18. //
  19. // Increment I by one.  Uses a RWSTDMutex directly.
  20. //
  21.  
  22. void increment_I ()
  23. {
  24.    I_mutex.acquire();  // Lock the mutex.
  25.    I++;
  26.    I_mutex.release();  // Unlock the mutex.
  27. }
  28.  
  29. //
  30. // Decrement I by one.  Uses a RWSTDGuard.
  31. //
  32.  
  33. void decrement_I ()
  34. {
  35.    RWSTDGuard guard(I_mutex);  // Acquire the lock on I_mutex.
  36.    --I;
  37.    //
  38.    // The lock on I is released when destructor is called on guard.
  39.    //
  40. }
  41.